import requests
import json
from abc import ABC, abstractmethod
from bs4 import BeautifulSoup
from app.db.database import SessionLocal
from app.db.crud import create_tpost, get_posts_count_with_title


class ContentFetcher(ABC):
    @abstractmethod
    def fetch_content(self):
        pass

    def save_content(self, content):
        with SessionLocal() as db:
            for item in content:
                title_get = item.get('title')
                if title_get is None:
                    continue
                #
                count = get_posts_count_with_title(db,title_get)
                if count == 0:
                    new_post = create_tpost(
                        db=db,
                        name=title_get,
                        title=title_get,
                        url=item.get('url'),
                        content="",
                        short_content="",
                        content_date=item.get('pub_date'),
                        is_judge=False,
                        is_user_define=False,
                        source_id=self.content_type
                    )

    def fetch_and_save(self):
        content = self.fetch_content()
        self.save_content(content)

    # 添加异步方法
    async def async_fetch_content(self):
        """异步获取内容的默认实现，子类可以重写此方法"""
        return self.fetch_content()

    async def async_save_content(self, content):
        """异步保存内容的默认实现"""
        self.save_content(content)

    async def async_fetch_and_save(self):
        """异步获取并保存内容"""
        content = await self.async_fetch_content()
        if content:
            self.save_content(content)  # 使用同步的save_content方法